// 点餐支付
import {getAccount, getAccountPayConfig} from "@src/api/member";
import {continuePayOrder, queryOrder} from "@src/api/catering";
import md5 from '@src/common/md5'

module.exports = Behavior({
  data: {
    accountInfo: {},
    accountPayRule: {}
  },
  ready: function () {
    this.$pay = this.selectComponent("#pay");
    this.getAccountInfo();
  },
  methods: {
    getAccountInfo() {
      getAccount().then(res => {
        this.setData({accountInfo: res.data})
      })
      getAccountPayConfig().then(res => {
        this.setData({accountPayRule: res.data})
      })
    },
    toCateringPay(options) {
      let {orderNo, payFee, hasDiscount, payChannels} = options;
      return new Promise(((resolve, reject) => {
        this.setData({payResolve: resolve, payReject: reject});
        let accountPayRule = this.data.accountPayRule;
        let accountInfo = this.data.accountInfo;
        let account = {balance: 0, canUseDiscount: false, requirePassword: false}
        if (accountInfo&&accountPayRule.useBalanceScope.indexOf(1) !=-1) {
          account = {
            balance: (accountInfo.balance||0)+(accountInfo.giftBalance||0)-(accountInfo.lockedBalance||0)-(accountInfo.lockedGiftBalance||0),
            canUseDiscount: accountPayRule.canUseDiscount,
            requirePassword: accountPayRule.canSkipPwd ? payFee > accountPayRule.skipPwdAmount : true
          }
        } else {
          if(payChannels.indexOf("balance") !== -1) {
            payChannels.splice(payChannels.indexOf("balance"), 1)
          }
        }
        this.$pay.openPay({
          payChannels: payChannels, account: account, payFee: payFee, hasDiscount: hasDiscount,
          confirm: (payChannel, password) => {
            if (payChannel === 'wx') {
              this.startWxPay(orderNo)
            } else {
              this.startBalancePay(orderNo, password)
            }
          },
          cancel: () => {
            // 用户取消支付, 跳转到订单详情页
            this._payFail();
          }
        })
      }))
    },
    startWxPay(orderNo) {
      continuePayOrder({orderNo, payType: 1}).then(res => {
        if (res.code === 0) {
          this.$pay.hideLoading();
          wx.requestPayment({
            'timeStamp': res.data.payTimestamp + '',
            'nonceStr': res.data.payNonceStr,
            'package': res.data.payPackage,
            'signType': res.data.paySignType,
            'paySign': res.data.paySignature,
            success: () => {
              this.$pay.showLoading();
              this.startPollOrderStatus(orderNo);
            },
            fail: () => {
              // 用户取消支付, 允许用户重新发起支付
              if (this.$pay.data.visible) {
                this.$pay.hideLoading();
              } else {
                this._payFail();
              }
            }
          })
        } else {
          // 直接回调支付失败,
          wx.showToast({title: res.msg, icon: "none", duration: 2000})
          this._payFail()
        }
      }).catch(error => {
        console.error(error)
        this._payFail()
      })
    },
    startBalancePay(orderNo, password) {
      if (password) {
        password = password//md5(password) 注释md5
      }
      return continuePayOrder({orderNo, balancePwd: password, payType: 3}).then(res => {
        if (res.code === 0) {
          this.startPollOrderStatus(orderNo);
        } else {
          // 刷新余额
          this.getAccountInfo();
          // 隐藏支付loading, 允许用户重新发起支付
          this.$pay.resetPassword();
          this.$pay.hideLoading();
          wx.showToast({title: res.msg, icon: "none", duration: 4000})
        }
      }).catch((error) => {
        console.info(error)
        if (error && error.msg) {
          // 刷新余额
          this.getAccountInfo();
          // 隐藏支付loading, 允许用户重新发起支付
          this.$pay.resetPassword();
          this.$pay.hideLoading();
          wx.showToast({title: error.msg, icon: "none", duration: 1500})
        } else {
          this._payFail();
        }
      })
    },
    startPollOrderStatus(orderNo) {
      this.setData({queryTimes: 1});
      this.innerQuery(orderNo);
    },
    innerQuery(orderNo) {
      if (this.data.queryTimes > 20) {
        this._payFail("查询支付状态超时");
        return;
      }
      queryOrder({orderNo}).then(res => {
        if (res.code !== 0) {
          this.setData({queryTimes: this.data.queryTimes + 1});
          this.innerQuery(orderNo);
          return;
        }
        let orderStatus = res.data.orderStatus;
        if (orderStatus === 3 || orderStatus === 6 || orderStatus === 7 || orderStatus === 8) {
          this._paySuccess();
        } else if (orderStatus === 4 || orderStatus === 5) {
          this._payFail("支付失败,请重试");
        } else {
          this.setData({queryTimes: this.data.queryTimes + 1});
          this.innerQueryOrderStatus(orderNo);
        }
      })
    },
    _paySuccess() {
      this.$pay.hideLoading();
      this.$pay.close();
      this.data.payResolve();
    },
    _payFail(reason, msg) {
      if (msg) {
        wx.showToast({title: msg, icon: "none", duration: 4000})
      }
      this.$pay.hideLoading();
      this.$pay.close();
      this.data.payReject({reason: reason})
    }
  }
})
